Lumen & Gesso / website · lumengesso.com / app / admin / orders / [id] / editor.tsx
| 1 | 'use client'; |
| 2 | |
| 3 | import { useEffect, useRef, useState, useTransition } from 'react'; |
| 4 | import { useRouter } from 'next/navigation'; |
| 5 | import { OPENAI_IMAGE_MODEL, resolveImageModel, SUPPORTED_MODELS, type ImageModel } from '@/app/lib/image-models'; |
| 6 | import { FramedPreview } from '@/app/components/FramedPreview'; |
| 7 | import type { FrameId } from '@/app/data/frames'; |
| 8 | import { sizeLabel, type ProductId, type Orientation } from '@/app/lib/pricing'; |
| 9 | import { OrderConversation } from '@/app/components/OrderConversation'; |
| 10 | import { OrderMessageTime } from '@/app/components/OrderMessageTime'; |
| 11 | import { ORDER_MESSAGE_LIMIT, PROOF_PUBLISH_STATUSES, STUDIO_MESSAGE_STATUSES, type activeProofRevision, type orderMessageConfig, type OrderMessage } from '@/app/lib/order-messages'; |
| 12 | |
| 13 | type Generation = { |
| 14 | id: string; |
| 15 | model: string; |
| 16 | prompt: string; |
| 17 | cleanUrl: string; |
| 18 | published: boolean; |
| 19 | /** Set by /api/orders/[id]/revise when the customer asks for changes |
| 20 | * on the generation that was current at that moment. Used to label |
| 21 | * prior generations in the History panel. Null = never rejected. */ |
| 22 | rejectedAt: string | null; |
| 23 | createdAt: string; |
| 24 | }; |
| 25 | |
| 26 | type FrameConfig = { |
| 27 | productId: ProductId; |
| 28 | size: string; |
| 29 | orientation: Orientation; |
| 30 | frame: FrameId; |
| 31 | matteId: string | null; |
| 32 | }; |
| 33 | |
| 34 | type MessagePurpose = 'proof' | 'message'; |
| 35 | |
| 36 | function GenerationSpinner({ large = false }: { large?: boolean }) { |
| 37 | return ( |
| 38 | <span className={`admin-editor__loader-spinner${large ? ' admin-editor__loader-spinner--lg' : ''}`} aria-hidden="true"> |
| 39 | <svg viewBox="0 0 32 32" fill="none"> |
| 40 | <circle cx="16" cy="16" r="13" stroke="currentColor" strokeWidth="2" strokeOpacity="0.18" /> |
| 41 | <circle cx="16" cy="16" r="13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeDasharray="20 60" /> |
| 42 | </svg> |
| 43 | </span> |
| 44 | ); |
| 45 | } |
| 46 | |
| 47 | type Props = { |
| 48 | orderId: string; |
| 49 | status: string; |
| 50 | currentProofId: string | null; |
| 51 | proofRevision: ReturnType<typeof activeProofRevision>; |
| 52 | sentRevisions: ReturnType<typeof orderMessageConfig>['sentRevisions']; |
| 53 | pendingFeedback: string; |
| 54 | petPhotoUrls: string[]; |
| 55 | customStyleUrl: string | null; |
| 56 | /** Cached GPT-4o Vision description of the customer's style ref. |
| 57 | * Null when admin hasn't clicked Analyze yet. When present, the |
| 58 | * initialPrompt the server passes us ALREADY contains this in a |
| 59 | * STYLE_REFERENCE_BLOCK_MARKER section — but we keep the raw text |
| 60 | * here so the editor can label the button "Re-analyze (last run X)" |
| 61 | * and so the splice logic below can replace the right block. */ |
| 62 | customStyleDescription: string | null; |
| 63 | customStyleAnalyzedAt: string | null; |
| 64 | /** Free-text note the customer left for the artist (custom-style |
| 65 | * orders). Empty string when none. */ |
| 66 | artistNote: string; |
| 67 | /** Customer revision requests (oldest first). When the order is in |
| 68 | * revision_requested, the latest is the change to address — we |
| 69 | * pre-fill the Refine box with it and show the list read-only. */ |
| 70 | revisions: Array<{ note: string; at: string }>; |
| 71 | messages: OrderMessage[]; |
| 72 | initialModel: ImageModel; |
| 73 | /** Per-model starter prompts. OpenAI gets the full prose image brief; |
| 74 | * Gemini gets the compact "ingredient" prompt. The editor keeps both |
| 75 | * and swaps the textarea on model switch, remembering edits per model. */ |
| 76 | initialPrompts: Record<ImageModel, string>; |
| 77 | /** The background colour the customer picked in the Builder (resolved |
| 78 | * to label + hex). Null when the style doesn't expose the picker |
| 79 | * (cubist/ukiyo-e/etc. carry their own ground) or when it's a custom- |
| 80 | * style commission (the upload defines the ground). When set, the |
| 81 | * initialPrompts already have a BACKGROUND COLOUR directive baked in |
| 82 | * at the top so the AI paints the surround in this hex. */ |
| 83 | customerBackground: { hex: string; label: string } | null; |
| 84 | /** The lettering choice for "named" portrait variants — the pet's |
| 85 | * name + font label. Null when the style doesn't allow lettering, |
| 86 | * the customer turned the toggle off, or it's a custom-style |
| 87 | * commission. When set, the initialPrompts already have a NAME |
| 88 | * LETTERING directive baked in so the AI renders the name. */ |
| 89 | customerLettering: { name: string; fontLabel: string } | null; |
| 90 | frameConfig: FrameConfig; |
| 91 | generations: Generation[]; |
| 92 | historyUnavailable: boolean; |
| 93 | }; |
| 94 | |
| 95 | /** Marker that anchors the splice — duplicated from image-gen.ts so |
| 96 | * this client component doesn't pull the server-only module in. Must |
| 97 | * stay in sync with `STYLE_REFERENCE_BLOCK_MARKER` over there. */ |
| 98 | const STYLE_REFERENCE_BLOCK_MARKER = '## STYLE REFERENCE (from your uploaded image)'; |
| 99 | |
| 100 | /** Splice a freshly-analyzed style description into the existing prompt. |
| 101 | * If the prompt already has a STYLE REFERENCE block, replace it in |
| 102 | * place (no stacking duplicates on re-analyze). If not, append a fresh |
| 103 | * block at the end. */ |
| 104 | function spliceStyleDescription(currentPrompt: string, description: string): string { |
| 105 | const block = [ |
| 106 | STYLE_REFERENCE_BLOCK_MARKER, |
| 107 | 'Use the following description (generated by analyzing the uploaded style reference) as your primary guide to the style, especially when generating via OpenAI image-edit which only sees the subject photo.', |
| 108 | '', |
| 109 | description.trim(), |
| 110 | ].join('\n'); |
| 111 | |
| 112 | const markerIdx = currentPrompt.indexOf(STYLE_REFERENCE_BLOCK_MARKER); |
| 113 | if (markerIdx === -1) { |
| 114 | const sep = currentPrompt.endsWith('\n\n') ? '' : currentPrompt.endsWith('\n') ? '\n' : '\n\n'; |
| 115 | return currentPrompt + sep + block; |
| 116 | } |
| 117 | // Marker exists — replace from the marker to end-of-string (the |
| 118 | // description block is always the last section we add). |
| 119 | return currentPrompt.slice(0, markerIdx).trimEnd() + '\n\n' + block; |
| 120 | } |
| 121 | |
| 122 | /** "2m ago" / "just now" — small helper for the Re-analyze label. */ |
| 123 | function relativeTime(iso: string | null): string { |
| 124 | if (!iso) return ''; |
| 125 | const diffMs = Date.now() - new Date(iso).getTime(); |
| 126 | const secs = Math.round(diffMs / 1000); |
| 127 | if (secs < 30) return 'just now'; |
| 128 | if (secs < 60) return `${secs}s ago`; |
| 129 | const mins = Math.round(secs / 60); |
| 130 | if (mins < 60) return `${mins}m ago`; |
| 131 | const hours = Math.round(mins / 60); |
| 132 | if (hours < 24) return `${hours}h ago`; |
| 133 | const days = Math.round(hours / 24); |
| 134 | return `${days}d ago`; |
| 135 | } |
| 136 | |
| 137 | export function AdminEditor(props: Props) { |
| 138 | const router = useRouter(); |
| 139 | const [model, setModel] = useState<ImageModel>(props.initialModel); |
| 140 | // Per-model prompts. Each model is prompted differently (OpenAI = full |
| 141 | // prose brief, Gemini = compact ingredient prompt), so we keep one |
| 142 | // prompt per model and show the active model's. Switching the Model |
| 143 | // dropdown swaps the textarea but preserves whatever you'd edited for |
| 144 | // each model — switching back restores your edits. |
| 145 | const [prompts, setPrompts] = useState<Record<ImageModel, string>>(props.initialPrompts); |
| 146 | const prompt = prompts[model]; |
| 147 | const [generating, setGenerating] = useState(false); |
| 148 | // Refine: free-text tweak ("same but with a red background") applied to |
| 149 | // the currently-selected generation. Steers on that render directly. |
| 150 | // When the customer has an open revision request, pre-fill it with |
| 151 | // their latest note so the admin can refine straight from it. |
| 152 | const latestRevision = props.revisions.length > 0 ? props.revisions[props.revisions.length - 1] : null; |
| 153 | const [refineText, setRefineText] = useState( |
| 154 | props.status === 'revision_requested' ? props.pendingFeedback || latestRevision?.note || '' : '', |
| 155 | ); |
| 156 | const refineField = useRef<HTMLTextAreaElement>(null); |
| 157 | const focusRefinement = useRef(false); |
| 158 | const [startingRevision, setStartingRevision] = useState(false); |
| 159 | const [revisionError, setRevisionError] = useState<string | null>(null); |
| 160 | // Which post-hoc action is in flight on the selected render, so we show |
| 161 | // a single loader (not two "Working…" buttons). Null when idle. |
| 162 | const [refineAction, setRefineAction] = useState<'refine' | 'finish' | null>(null); |
| 163 | const [orderEmailAction, setOrderEmailAction] = useState<MessagePurpose | null>(null); |
| 164 | const [orderEmailFeedback, setOrderEmailFeedback] = useState<{ purpose: MessagePurpose; text: string; warning: boolean } | null>(null); |
| 165 | const [drafting, setDrafting] = useState<MessagePurpose | null>(null); |
| 166 | const [draftError, setDraftError] = useState<{ purpose: MessagePurpose; text: string } | null>(null); |
| 167 | const [proofNote, setProofNote] = useState(''); |
| 168 | const [studioNote, setStudioNote] = useState(''); |
| 169 | const [sendingToPrinter, setSendingToPrinter] = useState(false); |
| 170 | const [printerError, setPrinterError] = useState<string | null>(null); |
| 171 | const [error, setError] = useState<string | null>(null); |
| 172 | const [selectedId, setSelectedId] = useState<string | null>(null); |
| 173 | const [showAdvanced, setShowAdvanced] = useState(false); |
| 174 | const [showReply, setShowReply] = useState(false); |
| 175 | const [revisionView, setRevisionView] = useState<'published' | 'draft' | 'print'>('print'); |
| 176 | const [revisionAction, setRevisionAction] = useState<'generate' | 'upscale' | null>(null); |
| 177 | const [refreshingRevision, refreshRevision] = useTransition(); |
| 178 | const revisionBusy = revisionAction !== null || refreshingRevision; |
| 179 | const [revisionPreview, setRevisionPreview] = useState<{ id: string; loaded: boolean } | null>(null); |
| 180 | const revisionArt = useRef<HTMLDivElement>(null); |
| 181 | const revealRevisionId = useRef<string | null>(null); |
| 182 | const [sentRevisionId, setSentRevisionId] = useState<string | null>(null); |
| 183 | const selected = props.generations.find(g => g.id === selectedId) |
| 184 | ?? props.generations.find(g => g.published) ?? props.generations[0] ?? null; |
| 185 | const published = props.generations.find(g => g.id === props.currentProofId) ?? null; |
| 186 | const proofRevision = props.proofRevision; |
| 187 | const revisionDraft = props.generations.find(g => g.id === proofRevision?.draftId) ?? null; |
| 188 | const printUpscale = proofRevision?.printUpscale; |
| 189 | const printDraft = props.generations.find(g => g.id === printUpscale?.generationId); |
| 190 | const chosenDraft = revisionView === 'draft' ? revisionDraft : printDraft ?? revisionDraft; |
| 191 | const revisionPreviewReady = revisionView !== 'published' && !!chosenDraft && revisionPreview?.id === chosenDraft.id && revisionPreview.loaded; |
| 192 | const revisionPreviewFailed = revisionView !== 'published' && !!chosenDraft && revisionPreview?.id === chosenDraft.id && !revisionPreview.loaded; |
| 193 | const setRevisionPreviewStatus = (id: string, loaded: boolean) => { |
| 194 | setRevisionPreview(previous => previous?.id === id && previous.loaded === loaded ? previous : { id, loaded }); |
| 195 | }; |
| 196 | useEffect(() => { |
| 197 | if (!revisionPreviewReady || revisionPreview?.id !== revealRevisionId.current) return; |
| 198 | revealRevisionId.current = null; |
| 199 | revisionArt.current?.scrollIntoView({ block: 'nearest' }); |
| 200 | }, [revisionPreview, revisionPreviewReady]); |
| 201 | const showProofWorkbench = !!published && (props.status === 'awaiting_approval' || !!proofRevision); |
| 202 | const canRefine = !!selected && PROOF_PUBLISH_STATUSES.includes(props.status); |
| 203 | const canStartRevision = props.status === 'awaiting_approval' && !!props.currentProofId; |
| 204 | useEffect(() => { |
| 205 | if (canRefine && focusRefinement.current) { |
| 206 | focusRefinement.current = false; |
| 207 | refineField.current?.focus(); |
| 208 | } |
| 209 | }, [canRefine]); |
| 210 | |
| 211 | const startRevision = async (note: string) => { |
| 212 | const generationId = props.currentProofId; |
| 213 | if (!canStartRevision || !generationId || startingRevision) return; |
| 214 | setStartingRevision(true); |
| 215 | setRevisionError(null); |
| 216 | try { |
| 217 | const res = await fetch(`/api/admin/orders/${props.orderId}/publish`, { |
| 218 | method: 'POST', |
| 219 | headers: { 'content-type': 'application/json' }, |
| 220 | body: JSON.stringify({ generationId, startRevision: true }), |
| 221 | }); |
| 222 | const data = await res.json().catch(() => null) as { ok?: boolean; error?: string } | null; |
| 223 | if (!res.ok || !data?.ok) { |
| 224 | if (res.status === 409) router.refresh(); |
| 225 | throw new Error(data?.error ?? 'Could not start the revision.'); |
| 226 | } |
| 227 | setSelectedId(generationId); |
| 228 | setRefineText(note); |
| 229 | focusRefinement.current = true; |
| 230 | router.refresh(); |
| 231 | } catch (error) { |
| 232 | setRevisionError(error instanceof Error ? error.message : 'Could not start the revision.'); |
| 233 | } finally { |
| 234 | setStartingRevision(false); |
| 235 | } |
| 236 | }; |
| 237 | |
| 238 | const useCustomerNote = (note: string) => { |
| 239 | if (canStartRevision) { |
| 240 | void startRevision(note); |
| 241 | return; |
| 242 | } |
| 243 | setRefineText(note); |
| 244 | refineField.current?.focus(); |
| 245 | }; |
| 246 | // Style-analysis state — local mirror of what the server has cached. |
| 247 | // analyzedAt is what we render next to "Re-analyze"; description we |
| 248 | // only keep to know "has it been analyzed at least once" for the |
| 249 | // button label. (The actual text lives in the prompt textarea |
| 250 | // already, spliced in via spliceStyleDescription.) |
| 251 | const [styleAnalyzedAt, setStyleAnalyzedAt] = useState<string | null>(props.customStyleAnalyzedAt); |
| 252 | const [hasStyleDescription, setHasStyleDescription] = useState<boolean>(!!props.customStyleDescription); |
| 253 | const [analyzing, setAnalyzing] = useState(false); |
| 254 | const [analyzeError, setAnalyzeError] = useState<string | null>(null); |
| 255 | |
| 256 | const requestGeneration = async (input: { model: ImageModel; prompt?: string; baseGenerationId?: string; finish?: boolean; upscale?: boolean; feedbackAt?: string; replaceDraftId?: string }) => { |
| 257 | const attemptId = crypto.randomUUID(); |
| 258 | let res: Response; |
| 259 | try { |
| 260 | res = await fetch(`/api/admin/orders/${props.orderId}/generate`, { |
| 261 | method: 'POST', |
| 262 | headers: { 'content-type': 'application/json', 'x-generation-attempt': attemptId }, |
| 263 | body: JSON.stringify(input), |
| 264 | }); |
| 265 | } catch { |
| 266 | router.refresh(); |
| 267 | throw new Error(`The connection ended before the studio received the result. Check History before trying again. Attempt: ${attemptId}`); |
| 268 | } |
| 269 | const data = await res.json().catch(() => null) as { error?: string; generation?: { id?: string } } | null; |
| 270 | if (res.ok && data?.generation?.id) { |
| 271 | setSelectedId(data.generation.id); |
| 272 | if (input.feedbackAt !== undefined) { |
| 273 | revealRevisionId.current = data.generation.id; |
| 274 | refreshRevision(() => router.refresh()); |
| 275 | } |
| 276 | else router.refresh(); |
| 277 | return; |
| 278 | } |
| 279 | if (!data?.error && (res.ok || res.status >= 500)) { |
| 280 | router.refresh(); |
| 281 | throw new Error(`The studio could not confirm the result. Check History before trying again. Attempt: ${attemptId}`); |
| 282 | } |
| 283 | if (res.status === 409) router.refresh(); |
| 284 | throw new Error(`${data?.error ?? `Generation failed (${res.status}).`} Attempt: ${attemptId}`); |
| 285 | }; |
| 286 | |
| 287 | const generateRevision = async (upscale = false) => { |
| 288 | if (!published || !proofRevision || generating || revisionBusy || (upscale && !revisionDraft)) return; |
| 289 | setGenerating(true); |
| 290 | setRevisionAction(upscale ? 'upscale' : 'generate'); |
| 291 | setRevisionError(null); |
| 292 | setRevisionView('print'); |
| 293 | try { |
| 294 | await requestGeneration({ |
| 295 | model: resolveImageModel(published.model) ?? OPENAI_IMAGE_MODEL, |
| 296 | baseGenerationId: published.id, |
| 297 | feedbackAt: proofRevision.feedback.at, |
| 298 | replaceDraftId: revisionDraft?.id, |
| 299 | upscale, |
| 300 | }); |
| 301 | } catch (e) { |
| 302 | setRevisionError(e instanceof Error ? e.message : 'Could not generate the revision.'); |
| 303 | } finally { |
| 304 | setRevisionAction(null); |
| 305 | setGenerating(false); |
| 306 | } |
| 307 | }; |
| 308 | |
| 309 | const onGenerate = async () => { |
| 310 | setGenerating(true); |
| 311 | setError(null); |
| 312 | try { |
| 313 | await requestGeneration({ model, prompt }); |
| 314 | } catch (e) { |
| 315 | setError(e instanceof Error ? e.message : 'Generate failed'); |
| 316 | } finally { |
| 317 | setGenerating(false); |
| 318 | } |
| 319 | }; |
| 320 | |
| 321 | /** Refine the selected generation by steering on it with a free-text |
| 322 | * tweak. The reference is that render's clean file (handled server- |
| 323 | * side); we just send the raw instruction + which render to base on. |
| 324 | * Use the current version of the engine that produced the pixels. */ |
| 325 | const onRefine = async () => { |
| 326 | if (!selected || !refineText.trim()) return; |
| 327 | const refineModel = resolveImageModel(selected.model) ?? OPENAI_IMAGE_MODEL; |
| 328 | setGenerating(true); |
| 329 | setRefineAction('refine'); |
| 330 | setError(null); |
| 331 | try { |
| 332 | await requestGeneration({ model: refineModel, prompt: refineText.trim(), baseGenerationId: selected.id }); |
| 333 | setRefineText(''); |
| 334 | } catch (e) { |
| 335 | setError(e instanceof Error ? e.message : 'Refine failed'); |
| 336 | } finally { |
| 337 | setGenerating(false); |
| 338 | setRefineAction(null); |
| 339 | } |
| 340 | }; |
| 341 | |
| 342 | /** Re-render the selected proof with the current OpenAI image model. */ |
| 343 | const onFinish = async () => { |
| 344 | if (!selected) return; |
| 345 | setGenerating(true); |
| 346 | setRefineAction('finish'); |
| 347 | setError(null); |
| 348 | try { |
| 349 | await requestGeneration({ model: OPENAI_IMAGE_MODEL, baseGenerationId: selected.id, finish: true }); |
| 350 | } catch (e) { |
| 351 | setError(e instanceof Error ? e.message : 'Finish failed'); |
| 352 | } finally { |
| 353 | setGenerating(false); |
| 354 | setRefineAction(null); |
| 355 | } |
| 356 | }; |
| 357 | |
| 358 | const sendOrderUpdate = async (generationId?: string, sendRevision = false, resumeReview = false) => { |
| 359 | const purpose = generationId ? 'proof' : 'message'; |
| 360 | const note = sendRevision ? '' : (generationId ? proofNote : studioNote).trim(); |
| 361 | if (sendRevision && (revisionBusy || !revisionPreviewReady)) return; |
| 362 | if (resumeReview && (!proofRevision || revisionBusy || generating)) return; |
| 363 | if (drafting || orderEmailAction || (!generationId && !note)) return; |
| 364 | setOrderEmailAction(purpose); |
| 365 | setOrderEmailFeedback(null); |
| 366 | setDraftError(null); |
| 367 | try { |
| 368 | const res = await fetch(`/api/admin/orders/${props.orderId}/publish`, { |
| 369 | method: 'POST', |
| 370 | headers: { 'content-type': 'application/json' }, |
| 371 | body: JSON.stringify({ |
| 372 | generationId, note, sendRevision, |
| 373 | ...(resumeReview && proofRevision ? { resumeProof: { generationId: proofRevision.baseGenerationId, feedbackAt: proofRevision.feedback.at } } : {}), |
| 374 | }), |
| 375 | }); |
| 376 | const data = await res.json().catch(() => null) as { error?: string; emailSent?: boolean } | null; |
| 377 | if (!res.ok) { |
| 378 | if (res.status === 409) router.refresh(); |
| 379 | throw new Error(data?.error ?? `Could not save your update (${res.status}).`); |
| 380 | } |
| 381 | if (generationId) setProofNote(''); |
| 382 | else { |
| 383 | setStudioNote(''); |
| 384 | setShowReply(false); |
| 385 | } |
| 386 | if (generationId) { |
| 387 | setRevisionView('print'); |
| 388 | if (sendRevision) setSentRevisionId(generationId); |
| 389 | } |
| 390 | setOrderEmailFeedback(data?.emailSent |
| 391 | ? { purpose, text: resumeReview ? 'Reply sent. The same proof is back in review.' : `${sendRevision ? 'Revised proof published' : generationId ? 'Proof published' : 'Message saved'} and sent by email.`, warning: false } |
| 392 | : { purpose, text: resumeReview ? 'Reply saved and proof review resumed. The email could not be sent.' : 'The update was saved on the order, but the email could not be sent.', warning: true }); |
| 393 | router.refresh(); |
| 394 | } catch (e) { |
| 395 | setOrderEmailFeedback({ purpose, text: e instanceof Error ? e.message : 'Could not save your update.', warning: true }); |
| 396 | } finally { |
| 397 | setOrderEmailAction(null); |
| 398 | } |
| 399 | }; |
| 400 | |
| 401 | const generateReply = async (purpose: MessagePurpose, generationId?: string) => { |
| 402 | if (drafting || orderEmailAction) return; |
| 403 | const setNote = purpose === 'proof' ? setProofNote : setStudioNote; |
| 404 | setDrafting(purpose); |
| 405 | setDraftError(null); |
| 406 | setOrderEmailFeedback(null); |
| 407 | try { |
| 408 | const res = await fetch(`/api/admin/orders/${props.orderId}/draft-reply`, { |
| 409 | method: 'POST', |
| 410 | headers: { 'content-type': 'application/json' }, |
| 411 | body: JSON.stringify({ purpose, generationId }), |
| 412 | }); |
| 413 | const data = await res.json().catch(() => null) as { draft?: string; error?: string } | null; |
| 414 | if (!res.ok || !data?.draft) { |
| 415 | if (res.status === 409) router.refresh(); |
| 416 | throw new Error(data?.error ?? 'Could not generate a draft.'); |
| 417 | } |
| 418 | const draft = data.draft; |
| 419 | setNote(current => current.trim() ? current : draft); |
| 420 | } catch (e) { |
| 421 | setDraftError({ purpose, text: e instanceof Error ? e.message : 'Could not generate a draft.' }); |
| 422 | } finally { |
| 423 | setDrafting(null); |
| 424 | } |
| 425 | }; |
| 426 | |
| 427 | const onAnalyzeStyle = async () => { |
| 428 | setAnalyzing(true); |
| 429 | setAnalyzeError(null); |
| 430 | try { |
| 431 | const res = await fetch(`/api/admin/orders/${props.orderId}/analyze-style`, { |
| 432 | method: 'POST', |
| 433 | }); |
| 434 | const data = await res.json().catch(() => null) as { |
| 435 | description?: string; |
| 436 | analyzedAt?: string; |
| 437 | error?: string; |
| 438 | } | null; |
| 439 | if (!res.ok || !data?.description) { |
| 440 | throw new Error(data?.error ?? `Analyze failed (${res.status})`); |
| 441 | } |
| 442 | // Splice the freshly-described style into the OpenAI prompt only — |
| 443 | // the description exists so OpenAI's single-image /images/edits can |
| 444 | // mimic a style it can't see. Gemini sees the style image directly |
| 445 | // and doesn't need it. Idempotent — re-running swaps the block in |
| 446 | // place. |
| 447 | setPrompts((p) => ({ |
| 448 | ...p, |
| 449 | [OPENAI_IMAGE_MODEL]: spliceStyleDescription(p[OPENAI_IMAGE_MODEL], data.description!), |
| 450 | })); |
| 451 | setStyleAnalyzedAt(data.analyzedAt ?? new Date().toISOString()); |
| 452 | setHasStyleDescription(true); |
| 453 | } catch (e) { |
| 454 | setAnalyzeError(e instanceof Error ? e.message : 'Analyze failed'); |
| 455 | } finally { |
| 456 | setAnalyzing(false); |
| 457 | } |
| 458 | }; |
| 459 | |
| 460 | const onSendToPrinter = async () => { |
| 461 | if (!confirm('Send this order to Prodigi? Once printed, it ships — no taking it back. The clean print file + shipping address should both be sanity-checked first.')) { |
| 462 | return; |
| 463 | } |
| 464 | setSendingToPrinter(true); |
| 465 | setPrinterError(null); |
| 466 | try { |
| 467 | const res = await fetch(`/api/admin/orders/${props.orderId}/send-to-printer`, { |
| 468 | method: 'POST', |
| 469 | }); |
| 470 | if (!res.ok) { |
| 471 | const data = await res.json().catch(() => null) as { error?: string } | null; |
| 472 | throw new Error(data?.error ?? `Send to printer failed (${res.status})`); |
| 473 | } |
| 474 | router.refresh(); |
| 475 | } catch (e) { |
| 476 | setPrinterError(e instanceof Error ? e.message : 'Send to printer failed'); |
| 477 | } finally { |
| 478 | setSendingToPrinter(false); |
| 479 | } |
| 480 | }; |
| 481 | |
| 482 | return ( |
| 483 | <div className="admin-editor"> |
| 484 | {showProofWorkbench && published && (() => { |
| 485 | const sentRevision = props.sentRevisions.findLast(revision => revision.generationId === published.id); |
| 486 | const previousProof = props.generations.find(g => g.id === sentRevision?.baseGenerationId); |
| 487 | const compareFrom = revisionDraft ? published : !proofRevision ? previousProof : undefined; |
| 488 | const preview = revisionView === 'published' && compareFrom ? compareFrom : chosenDraft ?? published; |
| 489 | const previewLabel = preview === printDraft ? 'Upscaled draft' : preview === revisionDraft ? 'Revision draft' : preview === published ? 'Published proof' : 'Previous proof'; |
| 490 | const dimensions = printDraft ? printUpscale : sentRevision?.printUpscale; |
| 491 | const publishedNote = props.messages.findLast(message => message.kind === 'proof' && message.generationId === published.id); |
| 492 | const previousPublishedNote = previousProof && props.messages.findLast(message => message.kind === 'proof' && message.generationId === previousProof.id); |
| 493 | const previewNote = previewLabel === 'Previous proof' ? previousPublishedNote : publishedNote; |
| 494 | const feedback = proofRevision?.feedback ?? sentRevision?.feedback; |
| 495 | const conversation = props.messages.filter(message => message !== publishedNote); |
| 496 | return ( |
| 497 | <section aria-label="Proof conversation" className="admin-editor__panel admin-editor__panel--wide proof-workbench"> |
| 498 | <div className="proof-workbench__art" ref={revisionArt}> |
| 499 | {compareFrom && ( |
| 500 | <div className="proof-workbench__versions" aria-label="Compare proofs"> |
| 501 | <button className="btn btn--secondary btn--sm" type="button" aria-pressed={preview === compareFrom} onClick={() => setRevisionView('published')}>{revisionDraft ? 'Published proof' : 'Previous proof'}</button> |
| 502 | <button className="btn btn--secondary btn--sm" type="button" aria-pressed={preview === (revisionDraft ?? published)} onClick={() => setRevisionView('draft')}>{revisionDraft ? 'Revision draft' : 'Published proof'}</button> |
| 503 | {printDraft && <button className="btn btn--secondary btn--sm" type="button" aria-pressed={preview === printDraft} onClick={() => setRevisionView('print')}>Upscaled draft</button>} |
| 504 | </div> |
| 505 | )} |
| 506 | <FramedPreview |
| 507 | key={preview.id} |
| 508 | src={preview.cleanUrl} |
| 509 | alt={previewLabel} |
| 510 | {...props.frameConfig} |
| 511 | onImageLoad={preview === revisionDraft || preview === printDraft ? () => setRevisionPreviewStatus(preview.id, true) : undefined} |
| 512 | onImageError={preview === revisionDraft || preview === printDraft ? () => setRevisionPreviewStatus(preview.id, false) : undefined} |
| 513 | /> |
| 514 | <p className="admin-editor__framedmeta"> |
| 515 | {previewLabel} · {sizeLabel(props.frameConfig.productId, props.frameConfig.size, props.frameConfig.orientation)} |
| 516 | </p> |
| 517 | </div> |
| 518 | <div className="proof-workbench__conversation"> |
| 519 | <h2 className="admin-editor__h">{revisionDraft ? 'Review revision draft' : 'Proof conversation'}</h2> |
| 520 | <p className="proof-workbench__muted"> |
| 521 | {revisionDraft ? 'This draft is based on the published proof. Only the studio can see it.' |
| 522 | : proofRevision ? 'The customer requested changes. This proof is open for revision.' |
| 523 | : sentRevision ? 'Revised proof sent. Awaiting customer review.' |
| 524 | : 'The customer can approve this proof or ask for changes.'} |
| 525 | </p> |
| 526 | {previewNote && <div className="proof-workbench__note"> |
| 527 | <div className="proof-workbench__message-meta"> |
| 528 | <strong>{previewLabel === 'Previous proof' ? 'Your previous proof note' : 'Your published note'}</strong> |
| 529 | <OrderMessageTime at={previewNote.at} /> |
| 530 | </div> |
| 531 | <p>{previewNote.note}</p> |
| 532 | </div>} |
| 533 | {feedback && ( |
| 534 | <div className="proof-workbench__feedback"> |
| 535 | <div className="proof-workbench__message-meta"> |
| 536 | <strong>{proofRevision ? 'What the customer said' : 'Customer feedback for this revision'}</strong> |
| 537 | <OrderMessageTime at={feedback.at} /> |
| 538 | </div> |
| 539 | <blockquote>{feedback.note}</blockquote> |
| 540 | </div> |
| 541 | )} |
| 542 | {revisionBusy && ( |
| 543 | <div className="admin-editor__inline-loader" role="status"> |
| 544 | <GenerationSpinner /> |
| 545 | <div className="admin-editor__inline-loader-copy"> |
| 546 | <strong>{revisionAction === 'upscale' ? 'Upscaling for print…' : revisionAction === 'generate' ? 'Generating revision…' : 'Loading updated proof…'}</strong> |
| 547 | {revisionAction && <span>{revisionAction === 'upscale' ? 'Enlarging and verifying the print file.' : 'Applying the customer’s feedback. This can take a minute or two.'}</span>} |
| 548 | </div> |
| 549 | </div> |
| 550 | )} |
| 551 | {revisionPreviewFailed && ( |
| 552 | <p className="auth__error" role="alert">The revision was saved, but its image couldn’t load. Reload this page or try another revision.</p> |
| 553 | )} |
| 554 | {dimensions && <p className="proof-workbench__muted"> |
| 555 | <strong>Print resolution</strong> {dimensions.original.width} × {dimensions.original.height} px → {dimensions.upscaled.width} × {dimensions.upscaled.height} px |
| 556 | </p>} |
| 557 | {chosenDraft ? ( |
| 558 | <div className="proof-workbench__actions"> |
| 559 | <div className="proof-workbench__buttons"> |
| 560 | <button type="button" className="btn btn--rose btn--md" onClick={() => void sendOrderUpdate(chosenDraft.id, true)} |
| 561 | disabled={generating || revisionBusy || !revisionPreviewReady || !!orderEmailAction || !!drafting || sentRevisionId === chosenDraft.id}> |
| 562 | {orderEmailAction === 'proof' ? 'Sending revision…' : chosenDraft === printDraft ? 'Send upscaled proof' : 'Send revised proof'} |
| 563 | </button> |
| 564 | {!printDraft && <button type="button" className="btn btn--secondary btn--md" onClick={() => void generateRevision(true)} |
| 565 | disabled={generating || revisionBusy || !revisionPreviewReady || !!orderEmailAction || sentRevisionId === chosenDraft.id}> |
| 566 | Upscale for print |
| 567 | </button>} |
| 568 | <button type="button" className="btn btn--secondary btn--md" onClick={() => void generateRevision()} |
| 569 | disabled={generating || revisionBusy || !!orderEmailAction || sentRevisionId === chosenDraft.id}> |
| 570 | Try another revision |
| 571 | </button> |
| 572 | </div> |
| 573 | {!revisionPreviewFailed && <p className="proof-workbench__muted"> |
| 574 | {revisionView === 'published' ? 'Select a draft to send it.' : !revisionPreviewReady ? 'Loading the revision preview…' |
| 575 | : 'Publishes the draft to the same proof page and emails the customer.'} |
| 576 | </p>} |
| 577 | </div> |
| 578 | ) : proofRevision ? ( |
| 579 | <div className="proof-workbench__actions"> |
| 580 | <button type="button" className="btn btn--rose btn--md" onClick={() => void generateRevision()} disabled={generating || revisionBusy}> |
| 581 | Generate revision |
| 582 | </button> |
| 583 | <p className="proof-workbench__muted">Applies this feedback to the published proof and creates a draft for you to review.</p> |
| 584 | </div> |
| 585 | ) : null} |
| 586 | {revisionError && <p className="auth__error" role="alert">{revisionError}</p>} |
| 587 | {orderEmailFeedback && <p role="status" className={orderEmailFeedback.warning ? 'auth__error' : 'proof-workbench__muted'}>{orderEmailFeedback.text}</p>} |
| 588 | {!orderEmailFeedback && sentRevisionId === published.id && <p role="status">Revised proof sent.</p>} |
| 589 | <OrderConversation messages={conversation} studioView /> |
| 590 | <button type="button" className="btn btn--secondary btn--sm" aria-expanded={showReply} onClick={() => setShowReply(open => !open)}> |
| 591 | {showReply ? 'Close reply' : 'Reply without changing artwork'} |
| 592 | </button> |
| 593 | {showReply && ( |
| 594 | <form onSubmit={event => { event.preventDefault(); void sendOrderUpdate(undefined, false, !!proofRevision); }}> |
| 595 | <label className="admin-editor__label" htmlFor="proof-chat-reply">Message to customer</label> |
| 596 | <textarea id="proof-chat-reply" className="admin-editor__textarea" rows={3} maxLength={ORDER_MESSAGE_LIMIT} |
| 597 | value={studioNote} onChange={event => setStudioNote(event.target.value)} disabled={!!orderEmailAction} required /> |
| 598 | <button type="button" className="btn btn--secondary btn--sm" onClick={() => void generateReply('message')} |
| 599 | disabled={!!orderEmailAction || !!drafting || !!studioNote.trim()}> |
| 600 | {drafting === 'message' ? 'Drafting reply…' : 'Draft reply'} |
| 601 | </button> |
| 602 | <button type="submit" className="btn btn--secondary btn--sm" disabled={generating || revisionBusy || !!orderEmailAction || !!drafting || !studioNote.trim()}> |
| 603 | {orderEmailAction === 'message' ? 'Sending…' : proofRevision ? 'Send reply and resume review' : 'Send reply'} |
| 604 | </button> |
| 605 | </form> |
| 606 | )} |
| 607 | {draftError && <p role="alert" className="auth__error">{draftError.text}</p>} |
| 608 | {canStartRevision && ( |
| 609 | <button type="button" className="btn btn--secondary btn--sm" disabled={startingRevision || generating} |
| 610 | onClick={() => void startRevision(props.pendingFeedback)}>Start a manual revision</button> |
| 611 | )} |
| 612 | <button type="button" className="proof-workbench__advanced" aria-expanded={showAdvanced} |
| 613 | onClick={() => setShowAdvanced(open => !open)}>{showAdvanced ? 'Hide history and editing tools' : 'Show history and editing tools'}</button> |
| 614 | </div> |
| 615 | </section> |
| 616 | ); |
| 617 | })()} |
| 618 | {!showProofWorkbench && (props.messages.length > 0 || STUDIO_MESSAGE_STATUSES.includes(props.status)) && ( |
| 619 | <section className="admin-editor__panel admin-editor__panel--wide"> |
| 620 | {props.messages.length > 0 |
| 621 | ? <OrderConversation messages={props.messages} studioView onUseNote={(canRefine || canStartRevision) && !generating && !startingRevision ? useCustomerNote : undefined} /> |
| 622 | : <h2 className="orderdetail__photoshead">Order conversation</h2>} |
| 623 | {canStartRevision && ( |
| 624 | <button type="button" className="btn btn--secondary btn--sm" style={{ marginTop: 10 }} |
| 625 | onClick={() => void startRevision(props.pendingFeedback)} disabled={startingRevision || generating}> |
| 626 | {startingRevision ? 'Opening revision…' : 'Start revision'} |
| 627 | </button> |
| 628 | )} |
| 629 | {revisionError && <p role="alert" className="auth__error">{revisionError}</p>} |
| 630 | {STUDIO_MESSAGE_STATUSES.includes(props.status) && ( |
| 631 | <form onSubmit={e => { e.preventDefault(); void sendOrderUpdate(); }} style={{ marginTop: 14 }}> |
| 632 | <label className="admin-editor__label" htmlFor="studio-order-note">Message to customer</label> |
| 633 | <textarea |
| 634 | id="studio-order-note" |
| 635 | className="admin-editor__textarea" |
| 636 | rows={3} |
| 637 | maxLength={ORDER_MESSAGE_LIMIT} |
| 638 | value={studioNote} |
| 639 | onChange={e => setStudioNote(e.target.value)} |
| 640 | disabled={!!orderEmailAction || drafting === 'message'} |
| 641 | required |
| 642 | /> |
| 643 | <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 8 }}> |
| 644 | <button type="button" aria-label="Generate reply for standalone message" className="btn btn--secondary btn--md" |
| 645 | onClick={() => generateReply('message')} disabled={!!drafting || !!orderEmailAction || !!studioNote.trim()}> |
| 646 | {drafting === 'message' ? 'Generating reply…' : 'Generate reply'} |
| 647 | </button> |
| 648 | <button type="submit" className="btn btn--secondary btn--md" disabled={!!drafting || !!orderEmailAction || !studioNote.trim()}> |
| 649 | {orderEmailAction === 'message' ? 'Sending…' : 'Email message to customer'} |
| 650 | </button> |
| 651 | </div> |
| 652 | {draftError?.purpose === 'message' && <p role="alert" className="auth__error">{draftError.text}</p>} |
| 653 | </form> |
| 654 | )} |
| 655 | {orderEmailFeedback?.purpose === 'message' && ( |
| 656 | <p role="status" className={orderEmailFeedback.warning ? 'auth__error' : 'admin-editor__hint'} style={{ marginTop: 10 }}> |
| 657 | {orderEmailFeedback.text} |
| 658 | </p> |
| 659 | )} |
| 660 | </section> |
| 661 | )} |
| 662 | {/* Top-of-page "Send to printer" gate — only shown after the |
| 663 | customer has approved (status = approved). Sits above all |
| 664 | other panels so it's unmistakable. */} |
| 665 | {props.status === 'approved' && ( |
| 666 | <section className="admin-editor__panel admin-editor__panel--wide admin-editor__printgate"> |
| 667 | <div className="admin-editor__printgate-head"> |
| 668 | <span className="admin-editor__printgate-eyebrow">Customer approved · awaiting your final review</span> |
| 669 | <h2 className="admin-editor__h" style={{ marginTop: 2 }}>Ready to send to printer</h2> |
| 670 | </div> |
| 671 | <p className="admin-editor__printgate-body"> |
| 672 | The customer approved the proof. Nothing has been sent to Prodigi yet — give the published clean file a final look (use the <strong>View full size ↗</strong> link below), confirm the shipping address looks right, then send. |
| 673 | </p> |
| 674 | <div className="admin-editor__printgate-actions"> |
| 675 | <button |
| 676 | type="button" |
| 677 | onClick={onSendToPrinter} |
| 678 | disabled={sendingToPrinter} |
| 679 | className="btn btn--rose btn--md" |
| 680 | > |
| 681 | {sendingToPrinter ? 'Sending to printer…' : 'Send to printer'} |
| 682 | </button> |
| 683 | </div> |
| 684 | {printerError && ( |
| 685 | <p className="auth__error" style={{ marginTop: 10 }}>{printerError}</p> |
| 686 | )} |
| 687 | </section> |
| 688 | )} |
| 689 | |
| 690 | {/* Custom style reference — broken out into its own prominent |
| 691 | panel ABOVE the subject photos when the customer paid for a |
| 692 | custom-style commission. Shown at large size so admin can |
| 693 | actually evaluate the style; flagged with a chip so it's |
| 694 | obvious this image is wired into the generation alongside |
| 695 | the subject photo. The Analyze button below converts the |
| 696 | image into a textual style description for OpenAI's |
| 697 | single-image-only /images/edits endpoint. */} |
| 698 | {props.customStyleUrl && ( |
| 699 | <section className="admin-editor__panel admin-editor__panel--customstyle"> |
| 700 | <div className="admin-editor__customstyle-head"> |
| 701 | <h2 className="admin-editor__h" style={{ margin: 0 }}> |
| 702 | <span aria-hidden="true">✦ </span>Custom style reference |
| 703 | </h2> |
| 704 | <span className="admin-editor__customstyle-chip">Included in generation</span> |
| 705 | </div> |
| 706 | <p className="admin-editor__customstyle-body"> |
| 707 | Customer uploaded this as the visual style to mimic. <strong>Gemini</strong> sees this image directly during generation. <strong>OpenAI</strong>’s image-edit endpoint only accepts one reference image — click <strong>Analyze style</strong> below to convert this image into a textual style description that gets injected into the prompt so OpenAI can mimic it without seeing the image. |
| 708 | </p> |
| 709 | <div className="admin-editor__customstyle-body-row"> |
| 710 | <a href={props.customStyleUrl} target="_blank" rel="noreferrer" title="Open full size in new tab" className="admin-editor__customstyle-link"> |
| 711 | {/* eslint-disable-next-line @next/next/no-img-element */} |
| 712 | <img src={props.customStyleUrl} alt="Customer-uploaded custom style reference" className="admin-editor__customstyle-img" /> |
| 713 | </a> |
| 714 | <div className="admin-editor__customstyle-actions"> |
| 715 | <button |
| 716 | type="button" |
| 717 | onClick={onAnalyzeStyle} |
| 718 | disabled={analyzing} |
| 719 | className={hasStyleDescription ? 'btn btn--secondary btn--md' : 'btn btn--rose btn--md'} |
| 720 | title="Send the style reference to GPT-4o Vision and paste a textual description into the prompt below." |
| 721 | > |
| 722 | {analyzing |
| 723 | ? 'Analyzing… (~5s)' |
| 724 | : hasStyleDescription |
| 725 | ? <>Re-analyze {styleAnalyzedAt && <span style={{ opacity: 0.7, fontWeight: 400, marginLeft: 6 }}>· last run {relativeTime(styleAnalyzedAt)}</span>}</> |
| 726 | : <>Analyze style <span aria-hidden="true">→</span> fill prompt</> |
| 727 | } |
| 728 | </button> |
| 729 | {hasStyleDescription && ( |
| 730 | <p className="admin-editor__customstyle-help"> |
| 731 | ✓ Description added to the <strong>OpenAI</strong> prompt (select the OpenAI model below and look for the “{STYLE_REFERENCE_BLOCK_MARKER}” section). Edit it freely — re-analyze swaps it in place. Gemini doesn’t need it; it sees the style image directly. |
| 732 | </p> |
| 733 | )} |
| 734 | {!hasStyleDescription && ( |
| 735 | <p className="admin-editor__customstyle-help"> |
| 736 | Required for the OpenAI model to honor the custom style. Gemini works without it. |
| 737 | </p> |
| 738 | )} |
| 739 | {analyzeError && <p className="auth__error" style={{ margin: 0 }}>{analyzeError}</p>} |
| 740 | </div> |
| 741 | </div> |
| 742 | </section> |
| 743 | )} |
| 744 | |
| 745 | {props.artistNote && ( |
| 746 | <section className="admin-editor__panel admin-editor__panel--note"> |
| 747 | <h2 className="admin-editor__h" style={{ margin: 0 }}> |
| 748 | <span aria-hidden="true">✎ </span>Note from the customer |
| 749 | </h2> |
| 750 | <p className="admin-editor__notebody">{props.artistNote}</p> |
| 751 | <p className="admin-editor__notehint"> |
| 752 | Baked into the generation prompts as a customer request — visible at the top of the textarea below. Edit there if you need to override. |
| 753 | </p> |
| 754 | </section> |
| 755 | )} |
| 756 | |
| 757 | <section className="admin-editor__panel"> |
| 758 | <h2 className="admin-editor__h"> |
| 759 | {props.customStyleUrl ? 'Subject photos (pet)' : 'Customer photos'} |
| 760 | </h2> |
| 761 | {(props.customerBackground || props.customerLettering) && ( |
| 762 | <div className="admin-editor__choices"> |
| 763 | {props.customerBackground && ( |
| 764 | <div className="admin-editor__bgbadge" title="Customer's chosen background colour — already baked into the generation prompts below."> |
| 765 | <span className="admin-editor__bgbadge-label">Background colour</span> |
| 766 | <span |
| 767 | className="admin-editor__bgbadge-swatch" |
| 768 | style={{ background: props.customerBackground.hex }} |
| 769 | aria-hidden="true" |
| 770 | /> |
| 771 | <span className="admin-editor__bgbadge-name">{props.customerBackground.label}</span> |
| 772 | <code className="admin-editor__bgbadge-hex">{props.customerBackground.hex}</code> |
| 773 | </div> |
| 774 | )} |
| 775 | {props.customerLettering && ( |
| 776 | <div className="admin-editor__bgbadge" title="Customer's chosen lettering — already baked into the generation prompts below."> |
| 777 | <span className="admin-editor__bgbadge-label">Lettering</span> |
| 778 | <span className="admin-editor__bgbadge-name">“{props.customerLettering.name}”</span> |
| 779 | <code className="admin-editor__bgbadge-hex">{props.customerLettering.fontLabel}</code> |
| 780 | </div> |
| 781 | )} |
| 782 | </div> |
| 783 | )} |
| 784 | {props.petPhotoUrls.length === 0 ? ( |
| 785 | <p style={{ color: 'var(--ink-soft)', fontSize: 14 }}>No photos uploaded yet (CF Images not wired).</p> |
| 786 | ) : ( |
| 787 | <> |
| 788 | {props.petPhotoUrls.length > 1 && ( |
| 789 | <p className="admin-editor__hint" style={{ marginTop: -4, marginBottom: 12 }}> |
| 790 | This order has {props.petPhotoUrls.length} pets — every photo is combined into a single portrait. |
| 791 | </p> |
| 792 | )} |
| 793 | <div className="admin-editor__photos"> |
| 794 | {props.petPhotoUrls.map((url, i) => ( |
| 795 | <div key={url} className="admin-editor__photoslot"> |
| 796 | {/* eslint-disable-next-line @next/next/no-img-element */} |
| 797 | <img src={url} alt={`Pet ${i + 1}`} /> |
| 798 | <a |
| 799 | href={url} |
| 800 | target="_blank" |
| 801 | rel="noreferrer" |
| 802 | className="admin-editor__photozoom" |
| 803 | title="Open full size in new tab" |
| 804 | aria-label={`Open pet photo ${i + 1} full size in new tab`} |
| 805 | > |
| 806 | ⤢ |
| 807 | </a> |
| 808 | </div> |
| 809 | ))} |
| 810 | </div> |
| 811 | </> |
| 812 | )} |
| 813 | </section> |
| 814 | |
| 815 | {(!showProofWorkbench || showAdvanced) && <> |
| 816 | {/* Generate panel is only useful during the design phase. Once |
| 817 | the customer has approved (status: approved, in_production, |
| 818 | shipped) or the order is cancelled, generating more variants |
| 819 | is dead-end — the published gen is the one that goes to |
| 820 | print and no further publishes are possible. */} |
| 821 | {(props.status === 'pending_design' || props.status === 'awaiting_approval' || props.status === 'revision_requested') && ( |
| 822 | <section className="admin-editor__panel"> |
| 823 | <h2 className="admin-editor__h">Generate</h2> |
| 824 | <label className="admin-editor__label"> |
| 825 | Model |
| 826 | <select value={model} onChange={(e) => setModel(e.target.value as ImageModel)} className="admin-editor__input"> |
| 827 | {SUPPORTED_MODELS.map(m => <option key={m} value={m}>{m}</option>)} |
| 828 | </select> |
| 829 | </label> |
| 830 | <label className="admin-editor__label"> |
| 831 | Prompt |
| 832 | <span className="admin-editor__hint"> |
| 833 | Each model has its own prompt — OpenAI uses the full image brief, Gemini uses the compact style-ingredient prompt. Switching models swaps the text; your edits per model are remembered. |
| 834 | </span> |
| 835 | <textarea |
| 836 | rows={14} |
| 837 | value={prompt} |
| 838 | onChange={(e) => setPrompts((p) => ({ ...p, [model]: e.target.value }))} |
| 839 | className="admin-editor__textarea" |
| 840 | spellCheck={false} |
| 841 | /> |
| 842 | </label> |
| 843 | <button |
| 844 | type="button" |
| 845 | onClick={onGenerate} |
| 846 | disabled={generating || !prompt.trim() || props.petPhotoUrls.length === 0} |
| 847 | className="btn btn--rose btn--md" |
| 848 | > |
| 849 | {generating ? 'Generating portrait…' : 'Generate'} |
| 850 | </button> |
| 851 | {error && <p role="alert" className="auth__error" style={{ marginTop: 8 }}>{error}</p>} |
| 852 | </section> |
| 853 | )} |
| 854 | |
| 855 | <section className="admin-editor__panel admin-editor__panel--wide"> |
| 856 | <h2 className="admin-editor__h"> |
| 857 | History ({props.generations.length}) {selected && <span style={{ fontWeight: 400, color: 'var(--ink-soft)', fontSize: 14 }}>· selected: {selected.model}</span>} |
| 858 | </h2> |
| 859 | {props.historyUnavailable ? ( |
| 860 | <p role="alert" className="auth__error">Render history couldn’t be loaded. Refresh this page before generating again.</p> |
| 861 | ) : props.generations.length === 0 && !generating ? ( |
| 862 | <p style={{ color: 'var(--ink-soft)', fontSize: 14 }}>No generations yet. Pick a model + prompt, hit Generate.</p> |
| 863 | ) : ( |
| 864 | <> |
| 865 | <div className="admin-editor__history"> |
| 866 | {/* Placeholder slot for the in-flight generation — sits at |
| 867 | the start of history (newest first) so it's where the |
| 868 | customer's eye lands. Removed when router.refresh() |
| 869 | brings the real generation back from the server. */} |
| 870 | {generating && ( |
| 871 | <div |
| 872 | className="admin-editor__histthumb admin-editor__histthumb--loading" |
| 873 | aria-label="Generating a new preview" |
| 874 | aria-busy="true" |
| 875 | > |
| 876 | <GenerationSpinner /> |
| 877 | <div className="admin-editor__loader-text">Generating…</div> |
| 878 | </div> |
| 879 | )} |
| 880 | {props.generations.map(g => { |
| 881 | const rejected = !!g.rejectedAt && !g.published; |
| 882 | const proofLabel = props.status === 'revision_requested' ? 'Previous proof' : 'Published'; |
| 883 | const titleParts = [ |
| 884 | g.model, |
| 885 | new Date(g.createdAt).toLocaleString(), |
| 886 | ]; |
| 887 | if (g.published) titleParts.push(proofLabel); |
| 888 | else if (rejected) titleParts.push(`REJECTED ${new Date(g.rejectedAt!).toLocaleString()}`); |
| 889 | return ( |
| 890 | <button |
| 891 | key={g.id} |
| 892 | type="button" |
| 893 | onClick={() => setSelectedId(g.id)} |
| 894 | className={`admin-editor__histthumb${selected?.id === g.id ? ' is-selected' : ''}${g.published ? ' is-published' : ''}${rejected ? ' is-rejected' : ''}`} |
| 895 | title={titleParts.join(' · ')} |
| 896 | > |
| 897 | {/* eslint-disable-next-line @next/next/no-img-element */} |
| 898 | <img src={g.cleanUrl} alt="" /> |
| 899 | {g.published && <span className="admin-editor__pubpill">{proofLabel}</span>} |
| 900 | {rejected && <span className="admin-editor__rejpill">Rejected</span>} |
| 901 | </button> |
| 902 | ); |
| 903 | })} |
| 904 | </div> |
| 905 | {generating && !selected && ( |
| 906 | <div className="admin-editor__preview-loader" role="status" aria-busy="true"> |
| 907 | <GenerationSpinner large /> |
| 908 | <div className="admin-editor__loader-text"> |
| 909 | Generating the first preview… |
| 910 | <span style={{ display: 'block', marginTop: 4, fontSize: 12, opacity: 0.7 }}>2K render — typically ~60 seconds.</span> |
| 911 | </div> |
| 912 | </div> |
| 913 | )} |
| 914 | {selected && (() => { |
| 915 | // Proofs are never watermarked: admin and customer both |
| 916 | // see the clean artwork that gets printed. |
| 917 | const postApproval = ['approved', 'in_production', 'shipped'].includes(props.status); |
| 918 | const previewSrc = selected.cleanUrl; |
| 919 | const frameSizeLabel = sizeLabel(props.frameConfig.productId, props.frameConfig.size, props.frameConfig.orientation); |
| 920 | const previewLabel = postApproval |
| 921 | ? `Final proof — ${props.frameConfig.productId === 'matted' ? 'Box Frame Matted Print' : 'Framed Canvas'} · ${frameSizeLabel}` |
| 922 | : `What the customer will see — ${props.frameConfig.productId === 'matted' ? 'Box Frame Matted Print' : 'Framed Canvas'} · ${frameSizeLabel}`; |
| 923 | return ( |
| 924 | <div className="admin-editor__preview"> |
| 925 | <div className="admin-editor__framed"> |
| 926 | <FramedPreview |
| 927 | src={previewSrc} |
| 928 | alt={postApproval ? "Final proof in customer's chosen frame" : "Selected generation in customer's chosen frame"} |
| 929 | productId={props.frameConfig.productId} |
| 930 | size={props.frameConfig.size} |
| 931 | orientation={props.frameConfig.orientation} |
| 932 | frame={props.frameConfig.frame} |
| 933 | matteId={props.frameConfig.matteId} |
| 934 | /> |
| 935 | <div className="admin-editor__framedmeta"> |
| 936 | {previewLabel} |
| 937 | </div> |
| 938 | </div> |
| 939 | <div className="admin-editor__previewmeta"> |
| 940 | {(() => { |
| 941 | const linkedRevision = props.sentRevisions.findLast(revision => revision.generationId === selected.id || revision.baseGenerationId === selected.id); |
| 942 | const feedback = selected.id === props.currentProofId |
| 943 | ? props.proofRevision?.feedback ?? linkedRevision?.feedback |
| 944 | : linkedRevision?.feedback ?? props.proofRevision?.feedback; |
| 945 | return feedback && <div className="proof-workbench__feedback"> |
| 946 | <div className="proof-workbench__message-meta"> |
| 947 | <strong>{linkedRevision ? 'Customer feedback' : 'Current revision request'}</strong> |
| 948 | <OrderMessageTime at={feedback.at} /> |
| 949 | </div> |
| 950 | <blockquote>{feedback.note}</blockquote> |
| 951 | </div>; |
| 952 | })()} |
| 953 | <div><strong>{selected.model}</strong> · {new Date(selected.createdAt).toLocaleString()}</div> |
| 954 | <details style={{ marginTop: 8 }}> |
| 955 | <summary style={{ cursor: 'pointer', color: 'var(--ink-soft)' }}>Prompt used</summary> |
| 956 | <pre style={{ whiteSpace: 'pre-wrap', fontSize: 12, color: 'var(--ink-soft)', marginTop: 8 }}>{selected.prompt}</pre> |
| 957 | </details> |
| 958 | {(() => { |
| 959 | // Show the Publish button ONLY when it would |
| 960 | // actually do something — i.e., the order is open |
| 961 | // for a new preview AND this generation isn't the |
| 962 | // one already published. In every other case it's |
| 963 | // just visual noise (or worse, looks clickable |
| 964 | // when it isn't). View clean stays always. |
| 965 | const orderOpen = PROOF_PUBLISH_STATUSES.includes(props.status); |
| 966 | const isPublishing = orderEmailAction === 'proof'; |
| 967 | const showPublish = orderOpen && !selected.published; |
| 968 | let statusNote: string | null = null; |
| 969 | if (selected.published && props.status === 'awaiting_approval') { |
| 970 | statusNote = 'This proof is currently with the customer for review.'; |
| 971 | } else if (selected.published && props.status === 'revision_requested') { |
| 972 | statusNote = 'Approval is paused. Use this proof as a starting point for the next render.'; |
| 973 | } else if (selected.published && props.status === 'approved') { |
| 974 | statusNote = 'Customer approved this proof — see the Send to printer panel above.'; |
| 975 | } else if (selected.published) { |
| 976 | statusNote = 'This generation has already been published.'; |
| 977 | } else if (props.status === 'awaiting_approval') { |
| 978 | statusNote = 'A different proof is with the customer. Start a revision to prepare its replacement.'; |
| 979 | } else if (!orderOpen) { |
| 980 | statusNote = `Order is in "${props.status}" — no new proofs can be published.`; |
| 981 | } |
| 982 | return ( |
| 983 | <> |
| 984 | {showPublish && ( |
| 985 | <label className="admin-editor__label" style={{ marginTop: 12 }}> |
| 986 | Message to send with this proof (optional) |
| 987 | <textarea |
| 988 | className="admin-editor__textarea" |
| 989 | rows={3} |
| 990 | maxLength={ORDER_MESSAGE_LIMIT} |
| 991 | value={proofNote} |
| 992 | onChange={e => setProofNote(e.target.value)} |
| 993 | disabled={!!orderEmailAction || drafting === 'proof'} |
| 994 | /> |
| 995 | </label> |
| 996 | )} |
| 997 | <div style={{ marginTop: 12, display: 'flex', gap: 8, flexWrap: 'wrap' }}> |
| 998 | {showPublish && ( |
| 999 | <> |
| 1000 | <button type="button" aria-label="Generate reply for proof" className="btn btn--secondary btn--md" |
| 1001 | onClick={() => generateReply('proof', selected.id)} disabled={!!drafting || !!orderEmailAction || !!proofNote.trim()}> |
| 1002 | {drafting === 'proof' ? 'Generating reply…' : 'Generate reply'} |
| 1003 | </button> |
| 1004 | <button |
| 1005 | type="button" |
| 1006 | onClick={() => sendOrderUpdate(selected.id)} |
| 1007 | disabled={!!drafting || !!orderEmailAction} |
| 1008 | className="btn btn--rose btn--md" |
| 1009 | > |
| 1010 | {isPublishing ? 'Publishing…' : 'Publish and email proof'} |
| 1011 | </button> |
| 1012 | </> |
| 1013 | )} |
| 1014 | {!showProofWorkbench && <a href={selected.cleanUrl} target="_blank" rel="noreferrer" className="btn btn--secondary btn--md">View full size ↗</a>} |
| 1015 | </div> |
| 1016 | {draftError?.purpose === 'proof' && <p role="alert" className="auth__error">{draftError.text}</p>} |
| 1017 | {orderEmailFeedback?.purpose === 'proof' && ( |
| 1018 | <p role="status" className={orderEmailFeedback.warning ? 'auth__error' : 'admin-editor__hint'}> |
| 1019 | {orderEmailFeedback.text} |
| 1020 | </p> |
| 1021 | )} |
| 1022 | {statusNote && ( |
| 1023 | <p className="admin-editor__publishnote">{statusNote}</p> |
| 1024 | )} |
| 1025 | {orderOpen && ( |
| 1026 | <div className="admin-editor__refine"> |
| 1027 | <label className="admin-editor__label" style={{ marginBottom: 0 }}> |
| 1028 | Refine this render |
| 1029 | <span className="admin-editor__hint"> |
| 1030 | Describe one change to make on the selected image. This creates a new render with {resolveImageModel(selected.model) ?? OPENAI_IMAGE_MODEL}. |
| 1031 | </span> |
| 1032 | <textarea |
| 1033 | ref={refineField} |
| 1034 | rows={2} |
| 1035 | value={refineText} |
| 1036 | onChange={(e) => setRefineText(e.target.value)} |
| 1037 | placeholder="e.g. same but with a red background" |
| 1038 | className="admin-editor__textarea" |
| 1039 | spellCheck={false} |
| 1040 | /> |
| 1041 | </label> |
| 1042 | {refineAction ? ( |
| 1043 | <div className="admin-editor__inline-loader" role="status" aria-busy="true"> |
| 1044 | <GenerationSpinner /> |
| 1045 | <span className="admin-editor__loader-text" style={{ textAlign: 'left' }}> |
| 1046 | {refineAction === 'finish' ? 'Finishing in OpenAI…' : 'Refining…'} |
| 1047 | <span style={{ display: 'block', fontSize: 12, fontWeight: 400, opacity: 0.75, marginTop: 2 }}> |
| 1048 | creating a new generation — this can take ~60s |
| 1049 | </span> |
| 1050 | </span> |
| 1051 | </div> |
| 1052 | ) : ( |
| 1053 | <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 8 }}> |
| 1054 | <button |
| 1055 | type="button" |
| 1056 | onClick={onRefine} |
| 1057 | disabled={generating || !refineText.trim()} |
| 1058 | className="btn btn--secondary btn--md" |
| 1059 | > |
| 1060 | Refine this render → |
| 1061 | </button> |
| 1062 | <button |
| 1063 | type="button" |
| 1064 | onClick={onFinish} |
| 1065 | disabled={generating} |
| 1066 | className="btn btn--secondary btn--md" |
| 1067 | title="Re-render the selected image with the current OpenAI model." |
| 1068 | > |
| 1069 | Finish in OpenAI → |
| 1070 | </button> |
| 1071 | </div> |
| 1072 | )} |
| 1073 | {props.revisions.length > 0 && ( |
| 1074 | <div className="admin-editor__custreq"> |
| 1075 | <span className="admin-editor__custreq-label"> |
| 1076 | Customer’s requested {props.revisions.length === 1 ? 'change' : 'changes'} |
| 1077 | </span> |
| 1078 | <ol className="admin-editor__custreq-list"> |
| 1079 | {props.revisions.map((r, i) => { |
| 1080 | const isLatest = i === props.revisions.length - 1; |
| 1081 | return ( |
| 1082 | <li key={i}> |
| 1083 | <span className="admin-editor__custreq-meta"> |
| 1084 | <OrderMessageTime at={r.at} /> |
| 1085 | {props.status === 'revision_requested' && isLatest ? ' · latest — pre-filled above' : ''} |
| 1086 | </span> |
| 1087 | <span className="admin-editor__custreq-note">“{r.note}”</span> |
| 1088 | </li> |
| 1089 | ); |
| 1090 | })} |
| 1091 | </ol> |
| 1092 | </div> |
| 1093 | )} |
| 1094 | <span className="admin-editor__hint" style={{ marginTop: 8 }}> |
| 1095 | <strong>Finish in OpenAI</strong> re-renders the selected image with {OPENAI_IMAGE_MODEL} at the standard OpenAI proof size. |
| 1096 | </span> |
| 1097 | </div> |
| 1098 | )} |
| 1099 | </> |
| 1100 | ); |
| 1101 | })()} |
| 1102 | </div> |
| 1103 | </div> |
| 1104 | ); |
| 1105 | })()} |
| 1106 | </> |
| 1107 | )} |
| 1108 | </section> |
| 1109 | </>} |
| 1110 | </div> |
| 1111 | ); |
| 1112 | } |